/**
 * 
 */
package com.steel.springsecurity.security;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Secures the database by updating user passwords.
 * 
 * @author Mularien
 */
public class DatabasePasswordSecurerBean extends JdbcDaoSupport {
	private PasswordEncoder passwordEncoder;
	@Autowired
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public void secureDatabase() {
		getJdbcTemplate().query("select username, password from users", new RowCallbackHandler(){
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				String username = rs.getString(1);
				String password = rs.getString(2);
				// Ch 4 Salt Exercise
				String encodedPassword = password.length() > 50 ? password : passwordEncoder.encode(password);
//				String encodedPassword = passwordEncoder.encodePassword(password, null);
				getJdbcTemplate().update("update users set password = ? where username = ?", 
						encodedPassword, 
						username);
				logger.debug("Updating password for username: "+username+" to: "+encodedPassword);
			}			
		});
	}
}
